package org.gikolet.ch2.android.io;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.gikolet.ch2.data.ThreadHeader;
import org.gikolet.ch2.io.Formatter;
import org.gikolet.ch2.io.Parser;

public class Ch2ThreadHeaderPAF implements Formatter<ThreadHeader>,
		Parser<ThreadHeader> {

	private static final Pattern SUBJECT_PTN = Pattern
			.compile("^(\\S*).dat<>(.*)\\(([0-9]*)\\)$");

	public String format(ThreadHeader subject) {
		StringBuilder sb = new StringBuilder(128);

		sb.append(subject.getThreadKey());
		sb.append(".dat");
		sb.append("<>");
		sb.append(subject.getSubject());
		sb.append(" (");
		sb.append(subject.getResCount());
		sb.append(")");

		return sb.toString();
	}

	public String format(List<ThreadHeader> subjects) {
		StringBuilder sb = new StringBuilder(128 * subjects.size());

		for (ThreadHeader s : subjects) {
			sb.append(format(s));
			sb.append('\n');
		}

		return sb.toString();
	}

	public ThreadHeader parse(String line) throws IOException {
		Matcher matcher = SUBJECT_PTN.matcher(line);

		if (!matcher.find()) {
			throw new IOException("Format is invalid.");
		}

		String key = matcher.group(1);
		Date date = new Date(Long.parseLong(key + "000"));

		ThreadHeader s = new ThreadHeader(null, key);

		s.setSubject(matcher.group(2));
		s.setResCount(Integer.parseInt(matcher.group(3)));
		s.setDate(date);

		return s;
	}
}
